<template>
  <div class="common-layout">
     <el-container>
         <el-header class="header_activate">
            <div class="draw">
                <el-drawer v-model="state.drawer" title="试卷增加题目" direction="ttb" size="60%">
                    <template #header>
                        <h4>修改导学案</h4>
                    </template>
                    <template #default>
                        <el-form :model="state.updatePaperForm" :rules="state.rules" ref="paperRef" label-width="100px" class="paperForm">
                            <el-form-item label="附件" prop="file"> 
                                <UploadDocxPptxFile ref="uploadDocxFileRef" :limit="5" :action="state.uploadGuidePaperFileServer" :father_method="getFileUrl"></UploadDocxPptxFile>   
                            </el-form-item>
                            <el-form-item label="标题：" prop="title">
                                <el-input v-model="state.updatePaperForm.title" clearable/>
                            </el-form-item>
                            <el-form-item label="说明：" prop="remark">
                                <el-input v-model="state.updatePaperForm.remark" clearable/>
                            </el-form-item>
                            <el-form-item label="类型：" prop="type">
                                <el-select v-model="state.updatePaperForm.type" class="m-2" placeholder="选择类型" size="small" @change="typeSelectChange">
                                    <el-option
                                    v-for="item in paperTypeOption"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value"
                                    />
                                </el-select>            
                            </el-form-item>
                            <el-form-item label="库币：" prop="bank_point">
                                <el-input-number v-model="state.updatePaperForm.bank_point"></el-input-number>
                            </el-form-item>
                            
                            <el-form-item>                                
                                <el-button type="warning" @click="state.drawer=false">取消</el-button>
                                <el-button type="success" @click="submitUpdatePaper()" >确定</el-button>
                            </el-form-item>
                        </el-form>
                    </template>
                    
                    <template #footer>                
                        <div style="flex: auto">
                        <el-button type="warning" @click="state.drawer=false">取消</el-button>                  
                        
                        </div> 
                    </template>
                </el-drawer>
            </div> 
            <div><h3>我上传的导学案/课件</h3></div>            
             <div class="search_activate" id="top_position"> 
                 <el-input v-model="state.input_keyword" placeholder="输入标题关键字" />
                 <el-button type="warning" :icon="Search" @click="searchClick"></el-button> 
             </div>
             <div class="filter">
                 <el-dropdown @command="handleCommand">
                     <span class="el-dropdown-link">
                         时间筛选
                     <el-icon class="el-icon--right">
                         <arrow-down />
                     </el-icon>
                     </span>
                     <template #dropdown>
                     <el-dropdown-menu>    
                        <el-dropdown-item command="0">无限制</el-dropdown-item>                    
                         <el-dropdown-item command="7">近7天</el-dropdown-item>
                         <el-dropdown-item command="15">近15天</el-dropdown-item>
                         <el-dropdown-item command="30">近30天</el-dropdown-item>
                         <el-dropdown-item command="60" disabled>近60天</el-dropdown-item>
                         <el-dropdown-item command="90">近90天</el-dropdown-item>
                         <el-dropdown-item command="180" >近半年</el-dropdown-item>                         
                     </el-dropdown-menu>
                     </template>
                 </el-dropdown>
             </div>
         </el-header>
         <el-divider />
         <el-main>
            <div><h3>说明：导学案/课件，只有被设置为上线和公有，才能被其他用户浏览</h3></div>
             <el-table class="tableClass" :data="state.paperList" stripe                   
                 :header-cell-style="{ background: '#eef1f6', color: '#606266' }"                    
                  border
             > 
                 <el-table-column type="index" width="45" label="序" />                         
                 <el-table-column width="190" property="title" label="标题" show-overflow-tooltip />
                 <el-table-column width="210" property="remark" label="说明" show-overflow-tooltip />
                 <el-table-column width="70" label="预览"> 
                      <template #default="scope"> 
                          <el-button size="small" type="primary" @click="viewPaperClick(scope.row.file)">预览</el-button>
                      </template>
                  </el-table-column>
                  <el-table-column width="80" property="open_level_cn" label="公开"/>
                  <el-table-column width="80" property="online_cn" label="上/下线"/>
                 <el-table-column width="115" property="add_date" label="日期"/> 
                 <el-table-column width="70" property="type_cn" label="类型"/> 
                 <el-table-column width="120" label="审核状态" show-overflow-tooltip >
                       <template #default="scope">
                            <el-text v-if="handleOnlineAndApplication(scope.row)==3">管理员拒绝。理由是：{{ scope.row.application_info.detail }}</el-text>
                            <el-text v-if="handleOnlineAndApplication(scope.row)==2 || handleOnlineAndApplication(scope.row)==4">等待管理员审核</el-text>                
                            <el-button v-if="handleOnlineAndApplication(scope.row)==5" text type="success" @click="onlineClick(scope.row.id)">申请上线</el-button>                           
                    </template> 
                </el-table-column>
                 <el-table-column align="center" width="80" label="操作" >                  
                     <template #default="scope">
                        <div class="operate">
                            <el-tooltip class="box-item" effect="dark" content="设为公开" placement="top" v-if="scope.row.open_level==='private'">                         
                                <el-icon style="width: 1em; height: 1em; margin-right: 8px" @click="SetPublicOrPrivateClick(scope.row.id,'public')">
                                    <Unlock />
                                </el-icon>
                            </el-tooltip>
                            <el-tooltip class="box-item" effect="light" content="设为私藏" placement="top" v-else>
                                <Lock style="width: 1em; height: 1em; margin-right: 8px" @click="SetPublicOrPrivateClick(scope.row.id,'private')" />
                            </el-tooltip>
                            <el-tooltip class="box-item" effect="dark" content="修改" placement="top"> 
                                <Edit style="width: 1em; height: 1em;" @click="updatePaperClick(scope.row,scope.row.id)" />
                            </el-tooltip>
                        </div>
                     </template>
                 </el-table-column>
             </el-table>
             <div><h3>温馨提醒：如果管理员拒绝上线，需要修改内容后，再申请上线</h3></div>
             <el-pagination
             background
             layout="total, pre, pager, next"
             :total="state.total"                
             :page-size="state.pageSize"            
             @current-change="handleCurrentChange"
             />
         </el-main>
         <ShowGuidePaperFileDialog ref="showGuidePaperFileDialog" :file="state.file"></ShowGuidePaperFileDialog>    
     </el-container>
 </div>
</template>
<script setup>

import { Search, Unlock, Lock, Top, Document, ArrowDown, Edit } from '@element-plus/icons-vue'
import {onMounted,  reactive, toRefs, ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import axios from '@/utils/axios'
import { uploadGuidePaperFileServer } from '@/utils'
import config from '~/config'
import ShowGuidePaperFileDialog from '@/components/ShowGuidePaperFileDialog.vue'

const showGuidePaperFileDialog = ref(null)
const paperTypeOption = [{ value : 1, label : '导学案',}, {value : 2,label : '课件',}]
const state = reactive({
    input_keyword: '',
    days: 0,
    applicationList: [],
    total: 0, // 总条数
    currentPage: 1, // 当前页
    pageSize: 10, // 分页大小
    lastGetPapersMethod: 'default',
    paperList:[],
    file: '',
    drawer:false,
    updatePaper_id:0,
    updatePaperForm:Object,
    uploadGuidePaperFileServer,
    rules: { // 规则
        title: [
            {required: 'true', message: '请填写试卷标题', trigger: ['change']}
        ],      
        type: [
            { required: 'true', message: '请选择类型', trigger: ['change'] }
        ],
        remark: [
            { required: 'true', message: '请填写描述', trigger: ['change'] }
        ],
        bank_point: [
            { required: 'true', message: '请填写库币', trigger: ['change'] },
            {type:"number" ,min: 1, max: 100, message: '大小要在1到100的整数', trigger: 'blur' }
        ],
        },
})
const paperRef=ref(null)

// 子组件upload返回过来的数据
const getFileUrl=(url)=>{    
    console.log("upload子组件传过来的",url)    
    ElMessage.success("文件上传成功！")
    state.updatePaperForm.file=url
  } 
//导学案是否在线
const handleOnlineAndApplication=(obj)=>{    
    // console.log("申请单:", obj.application_info)
    // 未申请上线过，则申请上线表单
    if(Object.keys(obj.application_info).length==0){
        return 5
    }else
    // 导学案已经上线
    if(obj.online==true){
        return 1
    }else
    // 导学案下线，且管理员未处理
    if(obj.online==false & obj.application_info.status==0){
        return 2
    }else
    // 导学案下线，且被管理员拒绝，则需要修改后再申请
    if(obj.online==false & obj.application_info.status==2){
        return 3
    }else
    if(obj.online==false & obj.application_info.status==3){
        return 4
    }
}
  
// 导学案是否申请过上线表单
  const hasApplication=(obj)=>{
    if (obj=={}) { 
        return false        
    }else {
        return true
        console.log("返回真")
    }
  }
// 读取默认导学案列表
const getPapersByDefault=()=>{
    let params = {
        days: state.days,
        page: state.currentPage,
        size: state.size,
    }
    state.lastGetPapersMethod = 'default'
    axios.get(`/GuidePaperModelViewSet/own_guide_paper/`, {params}).then(res => {
        if (res.code==200){
            console.log("获取录入导学案成功：", res)
            state.paperList = res.data.results
            state.total = res.total
        }else{       
            console.log("error", res.message)
        }
    })
    .catch((error)=>{
        console.log("获取录入试卷失败", error)
    })
}
// 通过搜索关键字得到导学案列表
const getPapersBySearch=()=>{
    let params = { 
        query_key: state.input_keyword,
        page: state.currentPage,
        size: state.size,
    }
    state.lastGetPapersMethod = 'search'
    axios.get(`/GuidePaperModelViewSet/search_own_guide_paper/`, {params}).then(res => {
        if (res.code==200){
            console.log("搜索结果：", res)
            state.paperList = res.data.results
            state.total = res.total
        }else{
            ElMessage.error("没有查询到记录")    
            console.log("error", res.message)
        }
    })
    .catch((error)=>{
        console.log("获取数据错误：", error)
    })
}
// 更新上次获得导学案列表
const updatePapersByLastTime=()=>{
    if(state.lastGetPapersMethod ==='default'){
        getPapersByDefault()    
    }else{
        getPapersBySearch()
    }
}
onMounted(() => {
    getPapersByDefault()    
})
//设置天数
const handleCommand=(command=7)=>{
 command = parseInt(command)
 state.days = command
 getPapersByDefault()
}
// 设置导学案/课件公开或私密
const SetPublicOrPrivateClick=(id, open_level)=>{  
    let params = {
    pk: id,
    type: 0,
    open_level: open_level,
    days: state.days,
    }
    axios.patch(`/GuidePaperModelViewSet/${params.pk}/set_own_guide_paper_open_level/`, params).then(res => {
        if (res.code==200){
            // console.log("申请列表：", res)
            ElMessage.success("公开程度操作成功，返回首页！")
            state.paperList = res.data.results
            updatePapersByLastTime()
        }else if(res.code==1021){
            ElMessage.error("学案id错误！")
        }        
        else if(res.code==1022){
            ElMessage.warning("此操作没有必要！")
            console.log("error", res)
        }else{
            ElMessage.error("此操作失败！")
        }
    })
    .catch((error)=>{
        console.log("获取数据错误：", error)
    })
}

// 滚到顶端
const scrollToTop=()=>{
 document.querySelector('#top_position').scrollIntoView(true);
}
//点击页码时触发
const handleCurrentChange = (newPage)=>{
    state.currentPage = newPage 
    if (state.lastGetPapersMethod == 'default'){
        getPapersByDefault()
    }else{
        getPapersBySearch()
    }
    scrollToTop()
}

//点击浏览导学案/课件文件的按钮事件处理
const viewPaperClick=(file)=>{ 
    file = config[import.meta.env.MODE].baseUrl_noapi + file
    showGuidePaperFileDialog.value.open(file)
}
// 点击搜索事件按钮处理
const searchClick=()=>{    
    console.log("要搜索试卷啦")
    getPapersBySearch()
}
//点击更新导学案信息按钮，并从试卷列表中，获取该试卷的数据，开启抽屉，
const updatePaperClick=(obj,id)=>{
    state.updatePaper_id=id
    console.log("选择的导学案是：",obj)
    state.updatePaperForm = obj
    state.drawer=true
}

  // 提交更新导学案信息
  const submitUpdatePaper=()=>{
    paperRef.value.validate((vaild, obj) => {
      if (vaild) {
        let params = {
          id: state.updatePaperForm.id,
          title: state.updatePaperForm.title,
          remark: state.updatePaperForm.remark,
          type: state.updatePaperForm.type,
          file: state.updatePaperForm.file,
        }
        axios.put(`/GuidePaperModelViewSet/${state.updatePaperForm.id}/`, params).then((result) => {
          if(result.code==200){
            ElMessage.success( '操作成功')
            updatePapersByLastTime()
            state.drawer=false
          }else{
            console.log("提交错误", result)
          }
        }).catch((error)=>{
          console.log("更新试卷错误：", error)
        })
      }else{                //输出表单没有通过的原因
        console.log("表单没有通过！",obj)
        for (let key in obj) {
          console.log("具体错误：",obj[key][0].message)          
        }   
      }
    })
  }

   // 申请导学案上线
   const onlineClick=(id)=>{
    let params={ paper:id }
    console.log("id", params['id'])
    axios.post(`/GuidePaperApplicationModelViewSet/`, params).then(res => {
          if (res.code==200){
              ElMessage.success("上线申请成功，请耐心等待管理员审核！")
              updatePapersByLastTime()
          }else if(res.code==1022){
              ElMessage.warning("你的申请已经提交，请耐心等待管理员审核！")
              console.log("error", res)
          }else{
            console.log("操作失败", res)
            ElMessage.error("此操作失败！")
          }
      })
      .catch((error)=>{
          console.log("获取数据错误：", error)
      })
  }
  // 选择类型后，赋值给表单的相应字段
  const typeSelectChange=(value)=>{
    // console.log("类型改变了", value)
    state.updatePaperForm.type=value
  }
</script>

<style scoped>
.search_activate {
 display: flex;
 flex-flow: row nowrap;
 /* justify-content: space-between; */
 align-items: center;
 margin: 0 auto;
 height: 30px;
}
.header_activate{
 display: flex;
 flex-flow: row nowrap;
 justify-content:flex-start;
 align-items: center;
 padding: 0px;
 height: 30px;
 width:800px;
}
span{
 font-family: 'Franklin Gothic Medium', 'Arial Narrow', Arial, sans-serif;
 font-size: medium;
}
.tableClass .cell{   
 padding: 0!important;
 height: 20px!important;
 line-height: 20px!important;
 text-align: center;
 font-size: 10px;
}
.filter{
    background-color: rgb(219, 226, 221);
}
.operate{
    display: flex;
    flex-flow: row nowrap;
    justify-content:space-between;
    align-items: center;
    padding: 2px;   
}
</style>